﻿using System.ComponentModel.DataAnnotations;
using System.Linq;

namespace HieloCostalegre
{
    partial class HieloCostalegreDataContext
    {
        partial void InsertBusiness(Business instance)
        {
            if(ContractAlreadyExists(instance))
                throw new ValidationException("El contrato que escogiste ya esta asignado a otro cliente");
            ExecuteDynamicInsert(instance);
        }

        partial void UpdateBusiness(Business instance)
        {
            if (ContractAlreadyExists(instance))
                throw new ValidationException("El contrato que escogiste ya esta asignado a otro cliente");
            ExecuteDynamicUpdate(instance);
        }

        private bool ContractAlreadyExists(Business instance)
        {
            HieloCostalegreDataContext db = new HieloCostalegreDataContext();

            var results = db.Businesses
                .Where(b => b.Contract == instance.Contract
                            && b.Id != instance.Id
                ).ToList<Business>();

            return results.Count > 0;
        }

        partial void InsertRefrigeratorAssignment(RefrigeratorAssignment instance)
        {
            if (RefrigeratorIsAlreadyAssignedDuringTheseDates(instance))
                throw new ValidationException("Este refrigerador ya esta asignado durante estas fechas.");
            ExecuteDynamicInsert(instance);
        }

        partial void UpdateRefrigeratorAssignment(RefrigeratorAssignment instance)
        {
            if (RefrigeratorIsAlreadyAssignedDuringTheseDates(instance))
                throw new ValidationException("Este refrigerador ya esta asignado durante estas fechas.");
            ExecuteDynamicUpdate(instance);
        }

        private bool RefrigeratorIsAlreadyAssignedDuringTheseDates(RefrigeratorAssignment instance)
        {
            HieloCostalegreDataContext db = new HieloCostalegreDataContext();

            var results = db.RefrigeratorAssignments
                .Where(ra => ra.RefrigeratorId == instance.RefrigeratorId
                             &&
                             (
                                 ra.To >= instance.From
                                 ||
                                 ra.From <= instance.To
                             )
                )
                .ToList<RefrigeratorAssignment>();
            return results.Count > 0;
        }
    }
}
